<template>
  <div class="fl-c">
    <flexbox class="fl-h" align="stretch">
      <xr-avatar
        :id="item.createUserId"
        :name="item.createUser.realname"
        :size="32"
        :src="item.createUser.img"
        :disabled="false"
        class="fl-h-img" />
      <div class="fl-h-b">
        <div class="fl-h-name">
          <span class="realname">
            <wx-open-data :openid="item.createUser.realname" />
          </span>
          <template v-if="showControl">
            <el-tag>
              {{ getActivityTypeName(item.activityType) + getRecordLogTypeName(item.type) }}
            </el-tag>
            <el-tag v-if="item.category" type="info">
              {{ item.category }}
            </el-tag>
          </template>
          <span v-else class="dynamic-name">{{ getDynamicName() }}</span>
        </div>
        <div class="fl-h-time">{{ item.createTime }}</div>
      </div>

      <!-- 编辑下不能是外勤签到 -->
      <el-dropdown
        v-if="canDelete && showControl && (hasDeleteAuth || (hasEditAuth && item.type !== 4))"
        v-model="dropdownShow"
        class="more-drop"
        style="top: 12px;"
        trigger="click"
        @command="handleCommand">
        <el-button
          :type="dropdownShow ? 'selected' : 'subtle'"
          style="padding: 4px;"
          icon="el-icon-more" />
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item
            v-if="hasEditAuth && item.type !== 4 && item.type !== 5"
            command="edit">
            {{ $t('crm.components.e25ee0620d89d347669fab0e82f6779d') }}
          </el-dropdown-item>
          <el-dropdown-item v-if="hasDeleteAuth" command="delete">
            {{ $t('crm.components.093f7eade705288419f561b8de5d91be') }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </flexbox>

    <div class="fl-b">
      <slot name="content" />

      <div
        v-if="!$slots.content"
        class="fl-b-content"
        @click="handleClick"
        v-html="logContent" />
      <!-- 1 跟进记录 4 外勤签到 -->
      <div v-if="[1, 4].includes(item.type)">
        <log-fields-view
          label-position="left"
          :max-show-count="2"
          show-colon
          :fields="getFieldList(item)"
        />
      </div>

      <flexbox
        v-if="item.img && item.img.length > 0"
        class="fl-b-images"
        wrap="wrap">
        <div
          v-for="(file, fileIndex) in item.img"
          :key="file.url"
          v-src:background-image="file.url"
          class="fl-b-img-item"
          @click="previewImg(item.img, fileIndex)" />
      </flexbox>

      <div v-if="item.file && item.file.length > 0">
        <flexbox
          v-for="(file, fileIndex) in item.file"
          :key="fileIndex"
          class="cell">
          <div class="cell-hd first-show">
            <i class="wk wk-file" />
          </div>
          <div
            class="cell-hd cell-label first-show"
            style="flex-shrink: 0;margin-right: 0;">
            {{ $t('crm.components.a69c53b88db80131c7a6a9c31aad2bfd') }}
          </div>
          <div class="cell-bd cell-label text-one-line">
            {{ file.name }}
          </div>
          <div class="cell-ft">
            <span class="des">（{{ file.size | getFileSize }}）</span>
            <a @click="previewImg(item.file, fileIndex)">
              {{ $t('crm.components.12ec99bf8a441f6cc97fc8a65f13f707') }}
            </a>
            <a @click="downloadFile(file)">
              {{ $t('crm.components.c5ffbd4e67d06032503d1e226ed301f8') }}
            </a>
          </div>
        </flexbox>
      </div>

      <!-- 关联业务 -->
      <div v-for="relative in relativeList" :key="relative.type">
        <flexbox align="stretch" class="cell">
          <div class="cell-hd ">
            <i :class="relative.icon" />
          </div>
          <div class="cell-bd cell-label">
            {{ relative.label }}
          </div>
          <div class="cell-ft">
            <div
              v-for="(relativeItem, relativeIndex) in item[relative.field]"
              :key="relativeIndex"
              class="cell-ft__item text-one-line">
              <a @click="checkRelationDetail(relative.type, relativeItem.id)">
                {{ relativeItem.name }}
              </a>
            </div>
          </div>
        </flexbox>
      </div>

      <div v-if="item.nextTime" class="cell-top">
        <flexbox align="stretch" class="cell">
          <div class="cell-hd">
            <i class="wk wk-time" />
          </div>
          <div class="cell-bd cell-label text-one-line">
            {{ nextTimeName }}：{{ item.nextTime }}
          </div>
        </flexbox>
      </div>

      <div v-if="item.type == 4" class="cell-top">
        <flexbox align="stretch" class="cell">
          <div class="cell-hd is-address">
            <i class="wk wk-icon-location" />
          </div>
          <div
            class="cell-bd text-one-line can-visit--underline"
            @click="checkMapView(item)">
            {{ addressContent }}
          </div>
        </flexbox>
      </div>
      <div
        v-if="(item.activityType === 13 || item.type === 5) && item.callRecord">
        <div class="cell">
          {{ $t('crm.components.77a2f501b07eaff4dada00f398f9f147',{1: typeArr[item.callRecord.type] ,2: stateArr[item.callRecord.state] }) }}
        </div>
        <div class="cell">
          {{ $t('crm.components.bcd1d4e3e15cde7175fa91a664db56f2',{1: item.callRecord.dialTime }) }}
        </div>
        <div class="cell">
          {{ $t('crm.components.f02a2937e0a2302e889ecb138f43558d',{1: item.callRecord.number }) }}
        </div>
        <div class="cell">
          <audios
            :props="audiosProps"
            :duration="item.talkTime"
            class="audios" />
          <el-button
            type="text"
            @click="download(item.callRecord.callRecordId, item.callRecord.fileName)">
            {{ $t('crm.components.275c5acfd389a87041a191d0533559da') }}
          </el-button>
          <!-- <el-popover
                  placement="left"
                  width="500"
                  trigger="click"
                  @show="popoverShow(item.callRecord)">
                  <div style="max-height: 50vh; overflow-y: auto; line-height: 1.5;">{{ item.callRecord.recordContent }}
                    <div v-loading="toStrLoading" element-loading-spinner="el-icon-loading" style="height: 40px;"/>
                  </div>
                  <el-button slot="reference" type="text" >转文字</el-button>
                </el-popover> -->
        </div>
      </div>

      <el-button
        v-if="showControl"
        type="icon"
        icon="wk wk-message"
        class="replay-btn"
        @click="replayClick">{{ (replyTotal > 0 ? `${replyTotal}` : '评论') }}</el-button>
    </div>

    <div
      v-if="showReply"
      class="reply-wrapper-wrap">
      <div
        class="reply-wrapper">
        <flexbox align="stretch" class="reply-comment-wrap">
          <xr-avatar
            :name="userInfo.realname"
            :size="32"
            :src="userInfo.img"
            class="user-img" />
          <reply-comment
            ref="f_reply"
            v-loading="commentLoading"
            :props="{
              contentType: commentListProps.contentType
            }"
            @toggle="closeOtherReply"
            @reply="handleReply" />
        </flexbox>
        <comment-list
          v-if="replyList.length > 0"
          ref="comment_list"
          :props="commentListProps"
          :list="replyList"
          @delete="deleteComment"
          @close-other-reply="$refs.f_reply.toggleFocus(true)" />
      </div>
    </div>

    <div
      v-if="[3, 5, 6, 7, 17, 18].includes(item.activityType) && crmType == 'customer'"
      class="cell-ft__item text-one-line follow-model">
      <span style="color: #6b778c;">相关{{ crmTypeModel.typeToNameData[item.activityType] }}-</span>
      <a @click="checkRelationDetail(crmTypeModel.typeToKeyData[item.activityType], item.activityTypeId)">{{ item.activityTypeName }}</a>
    </div>

    <map-view
      v-if="showMapView"
      :title="mapViewInfo.title"
      :lat="mapViewInfo.lat"
      :lng="mapViewInfo.lng"
      @hidden="showMapView=false" />

    <slot />
  </div>
</template>

<script>
import {
  crmActivityDeleteAPI,
  crmActivityOutworkSignDeleteAPI
} from '@/api/crm/common'
import {
  crmCallDownloadAPI
  // crmCallAudioToStrAPI
} from '@/api/bi/callCenter'
import {
  deleteCommentAPI,
  setCommentAPI,
  queryCommentListAPI
} from '@/api/oa/common'

import MapView from '@/components/MapView' // 地图详情
import Audios from '@/components/Audios'
import LogFieldsView from '@/views/oa/workLog/components/LogFieldsView'

import CommentList from '@/components/CommentList'
import ReplyComment from '@/components/ReplyComment'

import { downloadFile, fileSize, downloadFileWithBuffer } from '@/utils'
import XrSystemIconMixin from '@/mixins/XrSystemIcon'
import ActivityTypeMixin from './ActivityType'
import { mapGetters } from 'vuex'
import crmTypeModel from '@/views/crm/model/crmTypeModel'

export default {
  /** 客户管理 的 客户详情 的 跟进记录cell*/
  name: 'LogCell',
  components: {
    MapView,
    Audios,
    LogFieldsView,
    CommentList,
    ReplyComment
  },
  filters: {
    getFileSize(size) {
      return fileSize(size)
    }
  },
  mixins: [XrSystemIconMixin, ActivityTypeMixin],
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 块
    section: [String, Number],
    // 行
    index: [String, Number],
    canDelete: {
      type: Boolean,
      default: true
    },
    showControl: {
      type: Boolean,
      default: false
    },
    crmType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 控制展示地图详情
      showMapView: false,
      // 地图详情信息
      mapViewInfo: {},
      dropdownShow: false,
      toStrLoading: false,
      stateArr: [
        this.$t('crm.components.8ae194b30e954b7eb57eb205dbe0708e'),
        this.$t('crm.components.fcca6ceddab89aed7f747107777ac7cd'),
        this.$t('crm.components.537c96dbb7091b9f8f372d9d3a30d4e4'),
        this.$t('crm.components.67713f58cf77b3f7a8d3b8d98a0131bf')
      ],
      typeArr: [
        this.$t('crm.components.5f54a30514a47f6a6804da1f0b6894a2'),
        this.$t('crm.components.0f818bae0896a6a333e9f06468d984b6')
      ],
      // 评论
      commentLoading: false,
      showReply: false,
      replyList: []
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'crm']),
    hasEditAuth() {
      return this.crm && this.crm.followRecord && this.crm.followRecord.update
    },

    hasDeleteAuth() {
      return this.crm && this.crm.followRecord && this.crm.followRecord.delete
    },

    activityIcon() {
      return this.getXrIcon(this.getActivityType(this.item.activityType))
    },

    activityIconColor() {
      return this.getXrIconColor(this.getActivityType(this.item.activityType))
    },

    // 跟进内容
    logContent() {
      if (!this.item) return ''
      // 外勤签到
      if (this.item.type == 4) {
        return (this.item.content || {}).content
      }
      return this.item.content
    },

    // 外勤签到的地址
    addressContent() {
      if (!this.item && this.item.type != 4) return ''
      const address = (this.item.content || {}).address || ''
      return address.replace(/\,|，/g, '')
    },

    // 录音加载props
    audiosProps() {
      return {
        fileRequest: crmCallDownloadAPI, // 添加请求和参数
        fileParams: { id: this.item.callRecordId }
      }
    },

    // 关联业务
    relativeList() {
      const temp = [{
        field: 'customerList',
        type: 'customer',
        label: this.$t('crm.components.e5265da982a756b108458f6012f18659'),
        icon: 'wk wk-customer'
      }, {
        field: 'contactsList',
        type: 'contacts',
        label: this.$t('crm.components.c7bfc82aa6f5fff4a362f21323075398'),
        icon: 'wk wk-contacts'
      }, {
        field: 'businessList',
        type: 'business',
        label: this.$t('crm.components.1e7ab973d272c71e6035eaf8e3dbfc56'),
        icon: 'wk wk-business'
      }, {
        field: 'contractList',
        type: 'contract',
        label: this.$t('crm.components.9b31f61faa8a23ed139522d115d00797'),
        icon: 'wk wk-contract'
      }, {
        field: 'receivablesList',
        type: 'receivables',
        label: this.$t('crm.components.0bd16290154f8f7e469df7f912e95a5d'),
        icon: 'wk wk-receivables'
      }, {
        field: 'productList',
        type: 'product',
        label: '相关产品：',
        icon: 'wk wk-product'
      }]

      return temp.filter(o => this.item[o.field] && this.item[o.field].length > 0)
    },

    // 下次联系时间名称
    nextTimeName() {
      const nextTimeObj = (this.item.fieldList || []).find(item => item.fieldName === 'nextTime')
      return nextTimeObj?.name
    },

    // 评论列表配置
    commentListProps() {
      return {
        addRequest: setCommentAPI, // 添加请求和参数
        addParams: {
          titleName: this.item.activityTypeName,
          type: {
            leads: '4',
            customer: '5',
            contacts: '6',
            business: '7',
            contract: '8'
          }[this.getActivityType(this.item.activityType)],
          typeId: this.item.id,
          businessCreateUser: this.item.currentInfoCreateUser || this.item.createUserId
        },
        replyKey: 'pid', // 日志 任务 pid  阶段 replyId
        replyValueKey: 'userId', // 获取值的keys 日志 任务 userId  阶段 user.userId
        deleteRequest: deleteCommentAPI, // 删除请求和参数
        deleteParams: null,
        contentType: 'rich'
      }
    },
    replyTotal() {
      let num = 0
      this.replyList.forEach(item => {
        num++
        num += item.childCommentList.length || 0
      })
      return num || this.item.replyNum
    },

    crmTypeModel() {
      return crmTypeModel
    }
  },
  mounted() {},
  methods: {
    previewImg(list, index) {
      this.$wkPreviewFile.preview({
        index: index,
        data: list
      })
    },
    getFieldList(item) {
      const list = (item.fieldList || []).filter(o => !['content', 'nextTime', 'category', 'createUserName', 'createTime', 'activityTypeId'].includes(o.fieldName))
      return list
    },
    /**
     * 转文字框展示
     */
    // popoverShow(data) {
    //   this.$set(data, 'recordContent', '')
    //   this.getRecordContent({
    //     id: data.callRecordId
    //   }, data)
    // },
    // /**
    //  * 转文字
    //  */
    // getRecordContent(params, data, paramsArray, paramsIndex) {
    //   const postParams = { ...params }
    //   if (paramsArray) {
    //     postParams.fileStr = paramsArray[paramsIndex]
    //   }
    //   this.toStrLoading = true
    //   crmCallAudioToStrAPI(postParams).then(res => {
    //     const resData = res.data || {}
    //     const { dataStr, fileStr } = resData
    //     if (dataStr !== null) {
    //       data.recordContent = data.recordContent + dataStr.join('')
    //       this.toStrLoading = false
    //       if (paramsArray && paramsArray.length > paramsIndex + 1) {
    //         this.getRecordContent(params, data, paramsArray, paramsIndex + 1)
    //       }
    //     } else {
    //       const fileStrs = fileStr || []
    //       this.toStrLoading = false
    //       if (fileStrs.length > 0) {
    //         this.getRecordContent(params, data, fileStrs, 0)
    //       }
    //     }
    //   }).catch(() => {
    //     this.toStrLoading = false
    //   })
    // },
    /**
     * 音频下载
     */
    download(id, fileName) {
      crmCallDownloadAPI({ id: id }).then(res => {
        downloadFileWithBuffer(res.data, fileName)
      }).catch(() => {})
    },
    downloadFile(file) {
      downloadFile({ path: file.url, name: file.name })
    },
    /**
     * 删除跟进记录
     */
    handleCommand(command) {
      if (command == 'delete') {
        this.$confirm(
          this.$t('crm.components.5abcfbed2bc2dc2f9849a87d745b458d'),
          this.$t('crm.components.5ccfcbbf04460434d1aafd0364baf838'),
          {
            confirmButtonText: this.$t('crm.components.d0b885f8b4f5dd56f7f5a2bd12f50cda'),
            cancelButtonText: this.$t('crm.components.d6b0a0e619f7c2ef69e2ca060b751d32'),
            type: 'warning'
          }
        )
          .then(() => {
            const request = this.item.type == 4 ? crmActivityOutworkSignDeleteAPI : crmActivityDeleteAPI
            request({
              id: this.item.id
            })
              .then(res => {
                this.$emit('delete', this.item, this.index, this.section)
                // 刷新待办
                this.$store.dispatch('GetMessageNum')

                this.$message.success(this.$t('crm.components.cce866bd5e82ed9a5b54877e3f77df77'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (command == 'edit') {
        this.$emit('edit', this.item, this.index, this.section)
      }
    },

    handleClick(e) {
      const { tagName, dataset } = e.target
      if (tagName === 'SPAN') {
        // @进详情
        const { wkType, wkTypeId } = dataset
        if (!!wkType && wkType !== 'user' && !!wkTypeId) {
          this.checkRelationDetail(wkType, wkTypeId)
        }
      }
    },

    /**
     * 查看相关客户管理详情
     */
    checkRelationDetail(type, id) {
      this.$emit('crm-detail', type, id)
    },

    /**
     * 查看地图详情
     */
    checkMapView(item) {
      if (item.content) {
        this.mapViewInfo = {
          title: this.addressContent,
          lat: item.content.lat,
          lng: item.content.lng
        }
        this.showMapView = true
      }
    },

    /**
     * 获取动态操作
     */
    getDynamicName(data) {
      const { type, activityType } = this.item
      if (type == 2) {
        return this.$t('crm.components.5e854c2ef9d63fc52646fc203bfc8946', { 1: this.getActivityTypeName(activityType) })
      } else if (type == 3) {
        return this.$t('crm.components.ee95540cd653480cde29967821fa68bd', { 1: this.getActivityTypeName(activityType) })
      }
      return ''
    },

    /**
     * @description: 显示评论框
     * @return {*}
     */
    replayClick() {
      this.showReply = !this.showReply
      if (this.showReply) {
        this.$nextTick(() => {
          this.$refs['f_reply'].showNoFocus = true
        })
      }
      if (this.replyList.length == 0) {
        this.getCommentList()
      }
    },

    /**
     * 获取回复列表
     */
    getCommentList() {
      queryCommentListAPI({
        typeId: this.item.id,
        type: this.commentListProps.addParams.type
      })
        .then(res => {
          const list = res.data || []
          this.replyList = list
          // this.replyList = list.sort((a, b) => {
          //   return new Date(b.createTime) - new Date(a.createTime)
          // }) || []
        })
        .catch(() => {})
    },

    handleReply(data, atList) {
      this.commentLoading = true
      this.commentListProps.addRequest({
        content: data,
        atUserId: (atList || []).map(item => item.userId),
        pid: this.item.createUser?.userId,
        ...this.commentListProps.addParams
      }).then(res => {
        res.data.user = {
          userId: this.userInfo.userId,
          realname: this.userInfo.realname,
          img: this.userInfo.img
        }
        res.data.childCommentList = []
        // this.$emit('add-comment', {
        //   data: res.data,
        //   index: this.index
        // })
        this.replyList.push(res.data)
        this.commentLoading = false
        this.$nextTick(() => {
          this.showReply = true
          this.$refs['f_reply'].commentsTextarea = ''
          this.$refs['f_reply'].showNoFocus = true
        })
      }).catch(() => {
        this.commentLoading = false
      })
    },

    deleteComment(index) {
      this.replyList.splice(index, 1)
    },

    closeOtherReply(flag) {
      if (!flag && this.$refs.comment_list) {
        this.$refs.comment_list.closeReply()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/** 跟进记录相关的 日志 审批任务 日程 项目 公共css */
.fl-c {
  position: relative;
  padding: 12px 0 $--interval-base #{$--interval-base * 2};
  background-color: white;

  .follow-model {
    display: flex;
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    box-shadow: rgba(9, 30, 66, 0.25) 0 1px 1px, rgba(9, 30, 66, 0.31) 0 0 1px;

    &:hover {
      box-shadow: rgba(9, 30, 66, 0.25) 0 2px 4px, rgba(9, 30, 66, 0.31) 0 0 1px;
    }

    & > a {
      flex: 1;
    }
  }
}

/** 头部布局 名字 头像 */
.fl-h {
  .fl-h-img {
    margin-right: 8px;
  }

  .fl-h-b {
    .fl-h-name {
      font-weight: $--font-weight-primary;

      .realname {
        color: $--color-black;
      }

      .realname + .el-tag {
        margin-left: 16px;
      }

      .el-tag + .el-tag {
        margin-left: $--interval-base;
      }
    }

    .fl-h-time {
      margin-top: 2px;
      color: $--color-text-secondary;
    }
  }
}

/** 头部 右侧 布局 */
.fl-h-handle {
  width: auto;

  .fl-h-handle-name {
    margin-right: 6px;
  }
}

/** 内容区域 */
.fl-b {
  margin-top: 8px;
  margin-left: 40px;

  .fl-b-content {
    line-height: 18px;
    letter-spacing: 0.5px;
    word-wrap: break-word;
    white-space: pre-wrap;

    ::v-deep .wk-at-tag {
      color: #0052cc;
      cursor: pointer;
    }
  }

  .fl-b-images {
    width: 310px;
    margin-top: $--interval-base;

    .fl-b-img-item {
      position: relative;
      display: inline-block;
      width: 98px;
      height: 98px;
      margin: 0 4px 4px 0;
      cursor: pointer;
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
    }
  }
}

.dynamic-name {
  margin-left: 8px;
  color: $--color-text-regular;
}

/** 附件 */
.fl-b-files {
  margin-top: 10px;
}

/** 关联附件 联系人 客户 行布局 */
.cell-top {
}

.cell {
  padding-top: $--interval-base;

  &-hd {
    margin-right: $--interval-base;

    i {
      color: $--color-n500;
    }
  }

  &-hd.is-address {
    margin-top: -3px;

    i {
      font-size: 17px !important;
    }
  }

  &-hd.first-show {
    opacity: 0;

    .audios {
      width: 255px;
    }
  }

  &-label {
    color: $--color-n500;
  }

  &-ft {
    flex-shrink: 0;

    .des {
      color: $--color-text-secondary;
    }

    &__item {
      margin-bottom: 3px;

      a {
        color: $--color-primary;
      }

      a:hover {
        text-decoration: underline;
      }
    }

    &__item + &__item {
      margin-bottom: 5px;
    }

    a {
      color: $--color-primary;
    }

    a:hover {
      text-decoration: underline;
    }
  }
}

.cell:first-child {
  .first-show {
    opacity: 1;
  }
}

// .follow {
//   margin-left: $--interval-base;
//   .follow-info {
//     padding: 3px 8px;
//     background-color: $--color-n40;
//     color: $--color-n500;
//     border-radius: $--border-radius-base;
//     margin-right: 10px;
//     display: inline-block;
//   }
// }

// 更多操作
// .log-mark,
.more-drop {
  position: absolute;
  top: 15px;
  right: 0;
}

.el-icon-more {
  margin-left: 8px;
}

.log-fields-view {
  margin-top: 8px;
}

.replay-btn {
  padding-left: 0;
  margin-top: 8px;
}

.reply-wrapper-wrap {
  padding-left: 40px;
  margin-top: $--interval-base;
}

.reply-wrapper {
  padding: 20px 20px 10px;
  border: $--border-base;
  border-radius: $--border-radius-base;
}

.reply-comment-wrap {
  .user-img {
    margin-top: 5px;
    margin-right: $--interval-base;
  }

  .reply-comment {
    flex: 1;
  }
}

.comment-list {
  margin-top: #{$--interval-base * 2};
}

// 类型标示
// .log-mark {
//   &__label {
//     font-size: $--font-size-small;
//     color: $--color-text-secondary;
//   }
// }
</style>
